package com.demo.youxuanmall.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.demo.youxuanmall.entity.Category;
import com.demo.youxuanmall.entity.Product;
import com.demo.youxuanmall.service.CategoryService;
import com.demo.youxuanmall.service.ProductService;
import com.demo.youxuanmall.service.SystemSettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Controller
public class HomeController extends BaseController {
    
    private final CategoryService categoryService;
    private final ProductService productService;

    public HomeController(SystemSettingService systemSettingService, 
                          CategoryService categoryService,
                          ProductService productService) {
        super(systemSettingService);
        this.categoryService = categoryService;
        this.productService = productService;
    }

    @GetMapping("/")
    public String index(Model model) {
        log.info("首页请求开始处理...");
        
        // 检查Flash属性
        if (model.containsAttribute("success")) {
            log.info("检测到success Flash属性: {}", model.getAttribute("success"));
        }
        if (model.containsAttribute("error")) {
            log.info("检测到error Flash属性: {}", model.getAttribute("error"));
        }
        
        try {
            // 获取状态正常且未被删除的分类
            LambdaQueryWrapper<Category> categoryWrapper = new LambdaQueryWrapper<>();
            categoryWrapper.eq(Category::getStatus, 1)  // 只查询启用状态的分类
                          .eq(Category::getIsDeleted, 0)  // 只查询未删除的分类
                          .orderByAsc(Category::getSort);  // 按排序字段升序排序
            List<Category> categories = categoryService.list(categoryWrapper);
            model.addAttribute("categories", categories);
            log.info("成功加载分类数据，数量: {}", categories != null ? categories.size() : 0);
            
            // 获取上架状态且未被删除的商品
            LambdaQueryWrapper<Product> productWrapper = new LambdaQueryWrapper<>();
            productWrapper.eq(Product::getStatus, 1)  // 只查询上架状态的商品
                         .eq(Product::getIsDeleted, 0)  // 只查询未删除的商品
                         .orderByDesc(Product::getCreateTime);  // 按创建时间倒序排序
            List<Product> products = productService.list(productWrapper);
            model.addAttribute("products", products);
            log.info("成功加载商品数据，数量: {}", products != null ? products.size() : 0);
        } catch (Exception e) {
            log.error("加载首页数据发生错误", e);
            // 确保即使发生错误，也能展示页面
            model.addAttribute("categories", new ArrayList<>());
            model.addAttribute("products", new ArrayList<>());
        }
        
        log.info("首页请求处理完成，准备渲染模板");
        return "index";
    }
} 